package cn.cloudreal.cbms.resourceState.action;

import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import cn.cloudreal.cbms.common.util.Constants;
import cn.cloudreal.cbms.common.util.DatadicContext;
import cn.cloudreal.cbms.common.util.PageBean;
import cn.cloudreal.cbms.common.util.StringUtils;
import cn.cloudreal.cbms.resmonitor.service.ResMonitorService;
import cn.cloudreal.cbms.resourceState.service.ResStateService;
import cn.cloudreal.cbms.system.dao.UserInfoDao;
import cn.cloudreal.cbms.system.dao.impl.UserInfoDaoImpl;
import cn.cloudreal.cbms.system.service.OrganizaService;
import cn.cloudreal.cbms.system.service.UserInfoService;
import cn.cloudreal.cbms.vo.Dictionary;
import cn.cloudreal.cbms.vo.Mediasumm;
import cn.cloudreal.cbms.vo.Organiza;
import cn.cloudreal.cbms.vo.Project;
import cn.cloudreal.cbms.vo.ProjectMedium;
import cn.cloudreal.cbms.vo.PutInPlanMonth;
import cn.cloudreal.cbms.vo.SourcePlanYear;
import cn.cloudreal.cbms.vo.UserInfo;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Result;

/**
 * <p>
 * Title: ITC
 * </p>
 * <p>
 * Description:资源状态action类
 * </p>
 * <p>
 * Copyright: Copyright (c) 2010
 * </p>
 * <p>
 * Company:云恒瑞通
 * </p>
 * 
 * @author 夏加冬
 * @date 2012-7-9
 */
public class ResStateAction extends ActionSupport
{
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;

    /** 日志工具类实例 */
    private static final Logger log = Logger.getLogger(ResStateAction.class);

    /** 资源状态服务 */
    ResStateService resStateService;

    /** 项目媒介list */
    List<ProjectMedium> projectMediums;

    /** 媒体 */
    ProjectMedium projectMedium;
    
    /** 媒体 */
    ProjectMedium projectMedium2;
    
    String defultTime;

    /** 当前页 */
    int currentPage;

    /** 分页对象 */
    PageBean page;

    /** 资源状态 */
    String mediumStatus;
    /**获取地市的citycode*/
    private String contractCitycode; 
    
    /** 资源状态 */
    String oldMediumStatus;

    /** 总条数 */
    int sumCount;

    /** 预占状态的项目媒介条数 */
    int preCount;

    /** 审批中状态的项目媒介条数 */
    int peddingCount;

    /** 占用状态的项目媒介条数 */
    int occupyCount;

    /** 完成投放状态的项目媒介条数 */
    int finishPutCount;

    /** 完成结算状态的项目媒介条数 */
    int finishSetCount;

    /** 已中止状态的项目媒介条数 */
    int suspendedCount;

    /** 当前有哪些项目媒介id选中了 */
    String selectUnit;

    /** 当前有哪些项目媒介id选中了数组 */
    String[] selStrings;
    /** 媒体类型 */
    List<Dictionary> mediaTyList;
    /** 项目类型 */
    List<Dictionary> projectTyList;
    /** 全省 */
    List<Dictionary> allProvinceList;
    /** 部门科室 */
    List<Dictionary> departmentList;
    /** 媒体资源类型 */
    List<Dictionary> resourceList;
    /** 搜索分类 */
    int keyword;
    /** 搜索关键字 */
    private String mediaName;
    /**
     * 返回树形菜单字符串
     */
    private String flag;
    /**
     * 注入service 类
     */
    OrganizaService organizaService;
    /**
     * 组织架构
     */
    List<Organiza> organizaLists;
    /**
     * 部门科室显示的value
     */
    private String organizeValue;
    /**
     * 地市s
     */
    private Dictionary city;

    /**
     * 资源状态列表
     * 
     * @return String
     */
    public String preList()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter ResStateAction preList() method,return String");
        }
        try
        {
            // 实例化 page分页对象
            page = new PageBean(currentPage == 0 ? 1 : currentPage,
                    Constants.PAGE_SIZE);
            // 获取项目媒介状态数据字典里的值
            List<Dictionary> datalist = DatadicContext.getInstance()
                    .getDicDataListByCode("MJSYQK");
            // 媒体类型
            mediaTyList = DatadicContext.getInstance()
                    .getDicDataListByCode("MTLX");
            // 项目类型
            projectTyList = DatadicContext.getInstance()
                    .getDicDataListByCode("XMLX");
            // 地市
            allProvinceList = DatadicContext.getInstance().getDicDataListByCode("CITY");
            // 媒体资源类型
            resourceList = DatadicContext.getInstance()
                    .getDicDataListByCode("MTZYLX");
            // 获取当前session对象中所属城市
            UserInfo userInfo = (UserInfo) ServletActionContext.getRequest()
                    .getSession()
                    .getAttribute(Constants.SESSIONPRKEY);
            // 默认东莞
            city = DatadicContext.getInstance().getDatadicObject(userInfo.getUsercity(), Constants.CITY_AREA_CODE);
            defultTime = StringUtils.formatDateToString(new Date(),"yyyy-MM");
            // 非空
            if (null != userInfo)
            {
                //
                if (userInfo.getUserRole() != null)
                {
                    // 非空重置
                    if (userInfo.getUsercity() != null)
                    {
                        if (!"".equals(userInfo.getUsercity()))
                        {
                            city.setId(userInfo.getUsercity());
                            city.setDatavalue(userInfo.getCityName());
                        }
                    }
                    // 操作范围
                    String roleRange = userInfo.getUserRole().getRoleRange();
                    if (roleRange != null)
                    {

                        // 地市级
                        if ("2".endsWith(roleRange))
                        {
                            allProvinceList.clear();
                            Dictionary dictionary = (Dictionary) DatadicContext.getInstance()
                                    .getDatadicObject(city.getId(), "CITY");
                            allProvinceList.add(dictionary);

                        }
                        // 地市级和 个人
                        if ("3".endsWith(roleRange))
                        {
                            allProvinceList.clear();
                            Dictionary dictionary = (Dictionary) DatadicContext.getInstance()
                                    .getDatadicObject(city.getId(), "CITY");
                            allProvinceList.add(dictionary);
                            // 设置创建者
                            if (userInfo.getUserCode() != null)
                            {
                                if (projectMedium == null)
                                {
                                    projectMedium = new ProjectMedium();
                                    projectMedium.setCreator(userInfo.getUserCode());
                                    // 设置时间段
                                    projectMedium.setArrangeTime(StringUtils.formatDateToString(new Date(),
                                            "yyyy-MM"));
                                    Project project = new Project();
                                    project.setCity(city.getId());
                                    // 设置地市
                                    projectMedium.setProject(project);
                                }
                                else
                                {
                                    projectMedium.setCreator(userInfo.getUserCode());
                                }

                            }
                        }
                    }
                }
            }
            // 设置项目媒介的资源状态
            if (projectMedium == null)
            {
                projectMedium = new ProjectMedium();
                // 设置时间段
                projectMedium.setArrangeTime(StringUtils.formatDateToString(new Date(),
                        "yyyy-MM"));
                
                Project project = new Project();
                project.setCity(city.getId());
                // 设置地市
                projectMedium.setProject(project);
            }

            if (keyword == 0)
            {
                mediaName = "";
            }
            if (keyword == 1)
            {
                mediaName = mediaName.trim();
                projectMedium.setMediumName(mediaName); // 媒介名称
                
            }
            if (keyword == 2)
            {
                mediaName = mediaName.trim();
                projectMedium.getProject().setProjectName(mediaName);// 项目名称
                
            }
            if (keyword == 3)
            {
                mediaName = mediaName.trim();
                projectMedium.getProject().setProjectManager(mediaName);// 项目负责人
            }
            if(projectMedium2 == null)
            {
            projectMedium.setMediumStatus(mediumStatus);
            }
            else {
            projectMedium.setMediumStatus(projectMedium2.getMediumStatus());    
            }
            projectMediums = resStateService.getProjMediums(page, projectMedium);
            if (projectMediums != null)
            {
                for (int i = 0; i < projectMediums.size(); i++)
                {
                    //设置排期时间显示格式
                    projectMediums.get(i).setArrangeTime(projectMediums.get(i).getArrangeTime().substring(0,projectMediums.get(i).getArrangeTime().lastIndexOf("-")));
                    // 设置状态
                    for (int j = 0; j < datalist.size(); j++)
                    {
                        if (datalist.get(j)
                                .getId()
                                .equals(projectMediums.get(i).getMediumStatus()))
                        {
                            projectMediums.get(i)
                                    .setMediumStatus(datalist.get(j)
                                            .getDatavalue());
                            break;
                        }
                    }
                    // 设置媒体类型
                    for (int j = 0; j < mediaTyList.size(); j++)
                    {
                        if (mediaTyList.get(j)
                                .getId()
                                .equals(projectMediums.get(i)
                                        .getMediasumm()
                                        .getMediaType()))
                        {
                            projectMediums.get(i)
                                    .getMediasumm()
                                    .setMediaType(mediaTyList.get(j)
                                            .getDatavalue());
                            break;
                        }
                    }
                    // 设置项目类型
                    for (int j = 0; j < projectTyList.size(); j++)
                    {
                        if (projectTyList.get(j)
                                .getId()
                                .equals(projectMediums.get(i)
                                        .getProject()
                                        .getProjectType()))
                        {
                            projectMediums.get(i)
                                    .getProject()
                                    .setProjectType(projectTyList.get(j)
                                            .getDatavalue());
                            break;
                        }
                    }
                    // 设置地市
                    for (int j = 0; j < allProvinceList.size(); j++)
                    {
                        if (allProvinceList.get(j)
                                .getId()
                                .equals(projectMediums.get(i)
                                        .getProject()
                                        .getCity()))
                        {
                            projectMediums.get(i)
                                    .getProject()
                                    .setCity(allProvinceList.get(j)
                                            .getDatavalue());
                            break;
                        }
                    }
                    // 设置媒体资源类型
                    for (int j = 0; j < resourceList.size(); j++)
                    {
                        if (resourceList.get(j)
                                .getId()
                                .equals(projectMediums.get(i)
                                        .getMediaPrice()
                                        .getMediaResourceType()))
                        {
                            projectMediums.get(i)
                                    .getMediaPrice()
                                    .setMediaResourceType(resourceList.get(j)
                                            .getDatavalue());
                            break;
                        }
                    }
                    // 设置部门
                    projectMediums.get(i)
                            .getProject()
                            .setProjectSection(getOrganize(projectMediums.get(i)
                                    .getProject()
                                    .getProjectSection()));
                    // 设置项目负责人
                    UserInfo userInfo1 = resStateService.getUserInfo(projectMediums.get(i)
                            .getProject()
                            .getProjectManager());
                    if (userInfo1 != null && userInfo1.getUserName() != null)
                    {
                        projectMediums.get(i)
                                .getProject()
                                .setProjectManager(userInfo1.getUserName());
                    }
                }
            }
            // 获取总的项目媒介条数
            sumCount = resStateService.getsumCount(projectMedium);
            // 设置项目媒介的资源状态为预占
            projectMedium.setMediumStatus("1");
            preCount = resStateService.getcurrentCount(projectMedium);
            // 设置项目媒介的资源状态为呈批中
            projectMedium.setMediumStatus("2");
            peddingCount = resStateService.getcurrentCount(projectMedium);
            // 设置项目媒介的资源状态为占用
            projectMedium.setMediumStatus("3");
            occupyCount = resStateService.getcurrentCount(projectMedium);
            // 设置项目媒介的资源状态为完成投放
            projectMedium.setMediumStatus("4");
            finishPutCount = resStateService.getcurrentCount(projectMedium);
            // 设置项目媒介的资源状态为完成结算
            projectMedium.setMediumStatus("5");
            finishSetCount = resStateService.getcurrentCount(projectMedium);
            // 设置项目媒介的资源状态为已中止
            projectMedium.setMediumStatus("6");
            suspendedCount = resStateService.getcurrentCount(projectMedium);
            // 部门科室
            // 查询组织架构信息 获取当前节点集合
            organizaLists = new ArrayList<Organiza>();
            organizaLists = organizaService.getOrganizaByCity(city.getId());
            // 获取生成组织架构字符串
            flag = Constants.getOrganizaTree(organizaLists);
            if (projectMedium.getProject() == null)
            {
                organizeValue = "--部门科室--";
            }
            else
            {
                organizeValue = getOrganize(projectMedium.getProject()
                        .getProjectSection());
                if (projectMedium.getProject().getProjectSection() == null
                        || projectMedium.getProject()
                                .getProjectSection()
                                .length() == 0)
                {
                    organizeValue = "--部门科室--";
                }
            }

        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常信息 返回error
            log.error("Error ResStateAction preList() method,return String", e);
            return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit ResStateAction preList() method,return String");
        }
        return SUCCESS;
    }

    /**
     * 获取地市下的组织架构
     * @return
     */
    public String getOrganization()
    {
        // response 对象
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter out = null;
        try
        {
            // 获取PrintWriter对象
            ServletActionContext.getRequest().setCharacterEncoding(
                    Constants.STR_UTF);
            response.setContentType(Constants.STR_CHARSET);
            out = response.getWriter();
            if (null != contractCitycode
                    && !"".equals(contractCitycode)) {
                String contractorCityCode = URLDecoder.decode(contractCitycode, "UTF-8");
                // 查询组织架构信息 获取当前节点集合
                organizaLists = new ArrayList<Organiza>();
                organizaLists = organizaService.getOrganizaByCity(contractorCityCode);
                // 获取生成组织架构字符串
                String flagstr = Constants.getOrganizaTree(organizaLists);
                Map map = new HashMap<Object, Object>();
                map.put("flagstr", flagstr);
              
                JSONArray jo = JSONArray.fromObject(map);
                out.print(jo.toString());
                out.flush();
                out.close();
            }
        }
        catch (Exception e) 
        {
            e.printStackTrace();
            return ERROR;
        }
        return null;
    }
    /**
     * 资源状态设置
     * 
     * @return String
     */
    public String setProjectMediumState()
    {
        // 打印进入方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Enter ResStateAction setProjectMediumState() method,return String");
        }
        try
        {
            // 设置项目媒介的资源状态
            projectMedium = new ProjectMedium();
            projectMedium.setMediumStatus(mediumStatus);
            projectMedium2 = new ProjectMedium();
            projectMedium2.setMediumStatus(oldMediumStatus);
            selStrings = selectUnit.split(",");
            // 设置项目媒介状态
            resStateService.setProjectMediumStatus(selStrings, projectMedium);
        }
        catch (Exception e)
        {
            // TODO: handle exception 添加异常信息 返回error
            log.error("Error ResStateAction setProjectMediumState() method,return String",
                    e);
            return ERROR;
        }

        // 打印退出方法体日志
        if (log.isInfoEnabled())
        {
            log.info("Exit ResStateAction setProjectMediumState() method,return String");
        }
        return SUCCESS;
    }

    /**
     * 获取组织架构中的数据
     */

    public String getOrganize(String organizaListsid)
    {
        List<Organiza> organizaL = new ArrayList<Organiza>();
        Organiza organiza = new Organiza();
        organiza.setOrgCode(organizaListsid);
        // 查询组织架构信息 获取当前节点集合
        organizaL = organizaService.getOrganizas(organiza);
        String orgName = organizaL.get(0).getOrgName();
        return orgName;
    }

    public ResStateService getResStateService()
    {
        return resStateService;
    }

    public void setResStateService(ResStateService resStateService)
    {
        this.resStateService = resStateService;
    }

    public List<ProjectMedium> getProjectMediums()
    {
        return projectMediums;
    }

    public void setProjectMediums(List<ProjectMedium> projectMediums)
    {
        this.projectMediums = projectMediums;
    }

    public ProjectMedium getProjectMedium()
    {
        return projectMedium;
    }

    public void setProjectMedium(ProjectMedium projectMedium)
    {
        this.projectMedium = projectMedium;
    }

    public int getCurrentPage()
    {
        return currentPage;
    }

    public void setCurrentPage(int currentPage)
    {
        this.currentPage = currentPage;
    }

    public PageBean getPage()
    {
        return page;
    }

    public void setPage(PageBean page)
    {
        this.page = page;
    }

    public String getMediumStatus()
    {
        return mediumStatus;
    }

    public void setMediumStatus(String mediumStatus)
    {
        this.mediumStatus = mediumStatus;
    }

    public static long getSerialversionuid()
    {
        return serialVersionUID;
    }

    public static Logger getLog()
    {
        return log;
    }

    public int getSumCount()
    {
        return sumCount;
    }

    public void setSumCount(int sumCount)
    {
        this.sumCount = sumCount;
    }

    public int getPreCount()
    {
        return preCount;
    }

    public void setPreCount(int preCount)
    {
        this.preCount = preCount;
    }

    public int getPeddingCount()
    {
        return peddingCount;
    }

    public void setPeddingCount(int peddingCount)
    {
        this.peddingCount = peddingCount;
    }

    public int getOccupyCount()
    {
        return occupyCount;
    }

    public void setOccupyCount(int occupyCount)
    {
        this.occupyCount = occupyCount;
    }

    public int getFinishPutCount()
    {
        return finishPutCount;
    }

    public void setFinishPutCount(int finishPutCount)
    {
        this.finishPutCount = finishPutCount;
    }

    public int getFinishSetCount()
    {
        return finishSetCount;
    }

    public void setFinishSetCount(int finishSetCount)
    {
        this.finishSetCount = finishSetCount;
    }

    public int getSuspendedCount()
    {
        return suspendedCount;
    }

    public void setSuspendedCount(int suspendedCount)
    {
        this.suspendedCount = suspendedCount;
    }

    public String getSelectUnit()
    {
        return selectUnit;
    }

    public void setSelectUnit(String selectUnit)
    {
        this.selectUnit = selectUnit;
    }

    public List<Dictionary> getMediaTyList()
    {
        return mediaTyList;
    }

    public void setMediaTyList(List<Dictionary> mediaTyList)
    {
        this.mediaTyList = mediaTyList;
    }

    public List<Dictionary> getProjectTyList()
    {
        return projectTyList;
    }

    public void setProjectTyList(List<Dictionary> projectTyList)
    {
        this.projectTyList = projectTyList;
    }

    public List<Dictionary> getAllProvinceList()
    {
        return allProvinceList;
    }

    public void setAllProvinceList(List<Dictionary> allProvinceList)
    {
        this.allProvinceList = allProvinceList;
    }

    public List<Dictionary> getDepartmentList()
    {
        return departmentList;
    }

    public void setDepartmentList(List<Dictionary> departmentList)
    {
        this.departmentList = departmentList;
    }

    public String getMediaName()
    {
        return mediaName;
    }

    public void setMediaName(String mediaName)
    {
        this.mediaName = mediaName;
    }

    public int getKeyword()
    {
        return keyword;
    }

    public void setKeyword(int keyword)
    {
        this.keyword = keyword;
    }

    public String[] getSelStrings()
    {
        return selStrings;
    }

    public void setSelStrings(String[] selStrings)
    {
        this.selStrings = selStrings;
    }

    public String getFlag()
    {
        return flag;
    }

    public void setFlag(String flag)
    {
        this.flag = flag;
    }

    public OrganizaService getOrganizaService()
    {
        return organizaService;
    }

    public void setOrganizaService(OrganizaService organizaService)
    {
        this.organizaService = organizaService;
    }

    public List<Organiza> getOrganizaLists()
    {
        return organizaLists;
    }

    public void setOrganizaLists(List<Organiza> organizaLists)
    {
        this.organizaLists = organizaLists;
    }

    public String getOrganizeValue()
    {
        return organizeValue;
    }

    public void setOrganizeValue(String organizeValue)
    {
        this.organizeValue = organizeValue;
    }

    public List<Dictionary> getResourceList()
    {
        return resourceList;
    }

    public void setResourceList(List<Dictionary> resourceList)
    {
        this.resourceList = resourceList;
    }

    public ProjectMedium getProjectMedium2()
    {
        return projectMedium2;
    }

    public void setProjectMedium2(ProjectMedium projectMedium2)
    {
        this.projectMedium2 = projectMedium2;
    }

    public String getOldMediumStatus()
    {
        return oldMediumStatus;
    }

    public void setOldMediumStatus(String oldMediumStatus)
    {
        this.oldMediumStatus = oldMediumStatus;
    }

    public String getContractCitycode()
    {
        return contractCitycode;
    }

    public void setContractCitycode(String contractCitycode)
    {
        this.contractCitycode = contractCitycode;
    }

    public Dictionary getCity()
    {
        return city;
    }

    public void setCity(Dictionary city)
    {
        this.city = city;
    }

    public String getDefultTime()
    {
        return defultTime;
    }

    public void setDefultTime(String defultTime)
    {
        this.defultTime = defultTime;
    }


}
